<?php
declare(strict_types=1);
namespace app\core;

use PhpOffice\PhpWord\TemplateProcessor;
use think\facade\Request;
use app\common\service\WebSocketClient;


class Word
{

    public static function Template($list,$templateid,$pathData){
        $t_model=Relation::getModel('base_template');
        $map=[];
        $map[] =['id','=',$templateid];
        $map=Res::querymap($t_model,$map);
        $temInfo=$t_model->where($map)->find();
        if(Res::kv($temInfo,'template_file')==''){
            return  ['code'=>0,'msg'=>'模板文件不存在','data'=>$pathData];
        }

        $path=ltrim(Res::kv($temInfo,'template_file'),'/');
        $path = app()->getRootPath().'public/'.$path;
        if(!file_exists($path)){
            unset($pathData['pathdoc']);
            unset($pathData['pathpdf']);
            return  ['code'=>0,'msg'=>'模板文件不存在','data'=>$pathData];
        }
        $model = new TemplateProcessor($path);
        $tmp = $model->getVariables(); 
        $i=-1;
        $e=10000;
        $kv=[];
        foreach($tmp as $k=>$val){
            if($val=='i'){
                $i=$k;
            }
            if($val=='e'){
                $e=$k;
            }
            $kv[$val]=1;
        }
        
        foreach($tmp as $key=>$value){
            if($key<$i || $key>$e){
                if($value=='er_code'){
                    $qrCode=Res::kv($list,'er_code');
                    $model->setImageValue('er_code',['path'=>ltrim($qrCode,'/'),'width'=>60,'height'=>60]);
                }else{
                    $model->setValue($value, Res::kv($list,$value));
                }
            }
        }
        $items=$list['items'];
        $num=count($items);
        if($i>-1 && $num>0){
            $model->cloneRow('i',$num);
            $j=1;
            foreach($items as $itlist){
                foreach($itlist as $ky=>$v){
                    if(Res::kv($kv,$ky)==1){
                        $name=$ky.'#'.$j;
                        $model->setValue($name, $v);
                    }
                }
                $kname='i#'.$j;
                $model->setValue($kname, $j);
                $kname='e#'.$j;
                $model->setValue($kname, '');
                $j++;
            }
        }

        $outdoc=$pathData['pathdoc'];
        $outpdf=$pathData['pathpdf'];
        //生成新的word
        $model->saveAs($outdoc);

        $data=[
            'urldoc'=>'',
            'urlpdf'=>'',
        ];

        $socketdata = '{type:"file_process",cmd:"word2pdf",srcFile:"'.$outdoc.'",targetFile:"'.$outpdf.'"}';

        if(strtoupper(substr(PHP_OS,0,3))!=='WIN'){
            WebSocketClient::send($socketdata);
        }
        if(file_exists($outdoc)){
            $data['urldoc']=Request::domain().'/'.$pathData['urldoc'];
        }
        if(file_exists($outpdf)){
            $data['urlpdf']=Request::domain().'/'.$pathData['urlpdf'];
        }
        return  ['code'=>1,'msg'=>'文档正在生成中...','data'=>$data];
    }


}